import 'package:flutter/material.dart';
import 'package:icoreader/models/icon.dart';
import 'package:shirne_dialog/shirne_dialog.dart';

class IconPage extends StatefulWidget {
  final String file;

  const IconPage({Key? key, this.file = ''}) : super(key: key);

  @override
  State<IconPage> createState() => _IconPageState();
}

class _IconPageState extends State<IconPage> {
  IconModel model = IconModel();
  List<IconFileItem> lists = [];
  double itemWidth = 300;
  String ttxFile = '';
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    IconModel.transStepNotifier.addListener(onTransUpdate);
    onTransUpdate();
  }

  onTransUpdate() {
    model.getFiles().then((value) {
      setState(() {
        isLoading = false;
        lists = value;
      });
    });
  }

  delete(IconFileItem item) async {
    await model.deleteFile(item.file);
    onTransUpdate();
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return const CircularProgressIndicator();
    }

    if (lists.isEmpty) {
      return openNotice();
    }
    double width = MediaQuery.of(context).size.width;
    int count = width ~/ itemWidth;
    if (count < 1) {
      count = 1;
    }
    width = count * itemWidth;

    return Container(
      padding: const EdgeInsets.all(20),
      width: width,
      child: GridView.count(
          crossAxisCount: count,
          mainAxisSpacing: 10,
          crossAxisSpacing: 10,
          childAspectRatio: 3,
          children: lists
              .map<Widget>(
                (item) => Card(
                  child: Stack(
                    children: [
                      GestureDetector(
                        onTap: () {
                          if (item.isReady) {
                            Navigator.pushNamed(context, '/view',
                                arguments: item);
                          } else if (item.error.isEmpty) {
                            MyDialog.of(context).toast('正在处理');
                          } else {
                            MyDialog.of(context).alert(item.error);
                          }
                        },
                        child: Container(
                          color: Colors.transparent,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              const AspectRatio(
                                aspectRatio: 1,
                                child: Center(
                                  child: Icon(
                                    Icons.font_download_rounded,
                                    size: 70,
                                  ),
                                ),
                              ),
                              Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [Text(item.name)],
                              ),
                            ],
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.topRight,
                        child: AnimatedSwitcher(
                          duration: const Duration(milliseconds: 500),
                          child: item.isReady
                              ? const Icon(
                                  Icons.check_circle,
                                  color: Colors.green,
                                )
                              : item.error.isEmpty
                                  ? const Icon(
                                      Icons.refresh,
                                      color: Colors.grey,
                                    )
                                  : const Icon(
                                      Icons.error_rounded,
                                      color: Colors.red,
                                    ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.bottomRight,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            if (item.isReady)
                              IconButton(
                                onPressed: () {
                                  MyDialog.of(context)
                                      .confirm('确定删除图标文件(${item.name})？')
                                      .then((value) {
                                    if (value ?? false) {
                                      delete(item);
                                    }
                                  });
                                },
                                icon: const Icon(
                                  Icons.restore_from_trash_outlined,
                                  color: Colors.red,
                                ),
                              ),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
              )
              .toList()),
    );
  }

  Widget openNotice() {
    return const Text(
      '请点击右下角按钮选择字体文件',
      style: TextStyle(color: Colors.black26),
    );
  }
}
